package com.fauks.ssm.mybatis;

import com.fauks.ssm.mybatis.bean.MStudent;
import com.fauks.ssm.mybatis.mapper.DynamicSqlMapper;
import com.fauks.ssm.mybatis.utils.MyBatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

/**
 * 测试动态sql
 */
public class _03MyBatisTestDynamicSql {

    private SqlSession sqlSession;
    private DynamicSqlMapper dynamicSqlMapper;

    @Before
    public void initDao() {
        sqlSession = MyBatisUtils.getSqlSession();
        dynamicSqlMapper = sqlSession.getMapper(DynamicSqlMapper.class);
    }

    @After
    public void closeSession() {
        if (sqlSession != null) {
            sqlSession.close();
        }
    }

    @Test
    public void testSelectByIf() {
        MStudent student = new MStudent("f", 15);
        List<MStudent> stu = dynamicSqlMapper.getStuByIf(student);
        printStu(stu);
    }

    @Test
    public void testSelectByWhere() {
        MStudent student = new MStudent("", 15);
        List<MStudent> stu = dynamicSqlMapper.getStuByWhere(student);
        printStu(stu);
    }

    @Test
    public void testSelectByChoose() {
        MStudent student = new MStudent("", 0);
        List<MStudent> stu = dynamicSqlMapper.getStuByChoose(student);
        printStu(stu);
    }

    @Test
    public void testSelectByForEach() {
        int[] ids = {5, 20, 21};
        List<MStudent> stu = dynamicSqlMapper.getStuByForEach(ids);
        printStu(stu);
    }

    @Test
    public void testSelectByForEach2() {
        List<MStudent> students = new ArrayList<>();
        students.add(new MStudent(5));
        students.add(new MStudent(20));
        List<MStudent> stu = dynamicSqlMapper.getStuByForEach2(students);
        printStu(stu);
    }

    private void printStu(List<MStudent> stu) {
        for (MStudent student : stu) {
            System.out.println("id=" + student.getId() + ",name=" + student.getName() + ",age=" + student.getAge());
        }
    }

}
